import java.util.*;

public class Solution2 {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Queue<TreeNode> queue=new LinkedList<>();
        if(root==null){
            return res;
        }
        queue.offer(root);
        TreeNode cur;
        while(!queue.isEmpty()){
            int size=queue.size();
            for (int i = size; i >0; i--) {
                cur=queue.poll();
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
                if(i==1){
                    res.add(cur.val);
                }
            }
        }
        return res;
    }
}
